package com.itcoon.transform.base.register.annotated;

import com.itcoon.transform.base.exception.AssembleException;
import com.itcoon.transform.base.exception.TransformException;
import com.itcoon.transform.base.definition.ModelDefinition;
import com.itcoon.transform.base.register.AssembleModelRegister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.beans.IntrospectionException;
import java.util.List;

/**
 * @author Miaoxia Yu
 * @date 2020-10-26
 */
public class AnnotatedAssembleModelRegisterComposite {

    private static final Logger log = LoggerFactory.getLogger(AnnotatedAssembleModelRegisterComposite.class);

    @Autowired
    private List<AnnotatedAssembleModelRegister> assembleModelRegisters;

    /**
     * 寻找合适的注册器注册转换域的相关信息
     *
     * @param targetClass
     * @return
     */
    public ModelDefinition register(Class<?> targetClass) {
        ModelDefinition modelDefinition = new ModelDefinition();
        modelDefinition.setTargetClass(targetClass);
        for (AssembleModelRegister assembleModelRegister : assembleModelRegisters) {
            if (assembleModelRegister.support(targetClass)) {
                try {
                    assembleModelRegister.register(modelDefinition);
                } catch (IntrospectionException | NoSuchFieldException e) {
                    log.error(e.getMessage(), e);
                    throw new TransformException(e.getMessage());
                }
                return modelDefinition;
            }
        }
        throw new AssembleException("[Transform4j] - can not found any register process targetClass#" + targetClass.getName());
    }
}
